package com.crhms.seabow.security;

import com.crhms.seabow.model.AjaxResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class ForbiddenEntryPoint implements AuthenticationEntryPoint {

    private static final Log logger = LogFactory.getLog(ForbiddenEntryPoint.class);


    @Autowired
    private ObjectMapper objectMapper;
    /**
     * Always returns a 403 error code to the client.
     */
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException arg2) throws IOException, ServletException {
        if (logger.isDebugEnabled()) {
            logger.debug("Pre-authenticated entry point called. Rejecting access");
        }
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        PrintWriter out = response.getWriter();

        AjaxResponse ajaxResponse = new AjaxResponse();
        ajaxResponse.setStatus(403);
        ajaxResponse.setMsg("未登录");
        out.write(objectMapper.writeValueAsString(ajaxResponse));
        out.flush();
        out.close();
    }
}
